/**
 * 用法：
 * fetch的get方法、post方法
 */

/**
 * 转换对象参数为url参数拼接字符串
 * @param params url参数对象
 * @returns 拼接字符串
 */
function transferUrlParams<T extends object>(params: T): string {
  const entries = Object.entries(params);
  if (entries.length === 0) {
    return "";
  }
  return "?" + entries.map(([key, value]) => `${key}=${value}`).join("&");
}

/**
 * fetch的get请求方法
 * @param url url地址
 * @param params 参数可选
 * @returns Promise
 */
export async function get<RequestParams, ResponseData>(url: string, params?: RequestParams): Promise<ResponseData> {
  const urlParams = transferUrlParams(params ?? {});

  return fetch(url + urlParams, {
    method: "GET"
  }).then(data => data.json());
}

/**
 * fetch的post请求方法
 * @param url url地址
 * @param params body参数
 * @returns Promise
 */
export async function post<RequestParams, ResponseData>(url: string, params?: RequestParams): Promise<ResponseData> {
  const bodyParams = params ?? {};

  return fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json" // 请求头为json格式数据
    },
    body: JSON.stringify(bodyParams)
  }).then(data => data.json());
}

// 测试
/* const params = {
  a: 1,
  b: 2
};
console.log(transferUrlParams(params)); */
